package com.nuaa.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nuaa.model.hosp.Department;
import com.nuaa.vo.hosp.DepartmentQueryVo;
import com.nuaa.vo.hosp.DepartmentVo;
import com.nuaa.yygh.hosp.repository.DepartmentRepository;
import com.nuaa.yygh.hosp.service.DepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {

    //注入repository
    @Autowired
    private DepartmentRepository departmentRepository;


    //上传科室信息
    @Override
    public void save(Map<String, Object> paramMap) {
        //先将map转成字符串
        String jsonString = JSONObject.toJSONString(paramMap);
        //再将字符串转成Hospital对象
        Department department = JSONObject.parseObject(jsonString,Department.class);
        //判断是否存在,通过id和科室编号判断
        Department departmentExist = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(),department.getDepcode());
        //如果存在这个id就修改
        if(null != departmentExist) {
            departmentExist.setUpdateTime(new Date());
            departmentExist.setIsDeleted(0);
            departmentRepository.save(departmentExist);
        } else {
            //没有就进行添加
            //0：未上线 1：已上线
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> selectPage(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        //,通过什么样的描述进行升降序的排列
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");

        //0做第一页
        Pageable pageable = PageRequest.of(page-1,limit,sort);

        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo,department);
        department.setIsDeleted(0);

        //创建匹配器，（如何使用查询条件）
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        //创建实例
        Example<Department> example = Example.of(department, matcher);

        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;

    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(null !=department){
            departmentRepository.deleteById(department.getId());
        }
    }

    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //最终数据封装
        List<DepartmentVo> res = new ArrayList<>();

        Department department = new Department();
        department.setHoscode(hoscode);

        //创建带有hoscode的匹配器
        Example example = Example.of(department);

        List<Department> departmentList = departmentRepository.findAll(example);

        //运用java8新特性，根据大科室编号分组，获得每个大科室下的子科室
        Map<String,List<Department>> map =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        //遍历
        for(Map.Entry<String,List<Department>> entry : map.entrySet()){
            String bigcode = entry.getKey();
            //装大科室
            List<Department> bigDepartmentList = entry.getValue();
            //大科室封装
            DepartmentVo departmentVo = new DepartmentVo();
            departmentVo.setDepcode(bigcode);
            departmentVo.setDepname(bigDepartmentList.get(0).getBigname());

            //小科室封装
            List<DepartmentVo> childDepartmentVoList = new ArrayList<>();
            for(Department department1 :departmentList){
                DepartmentVo childDepartmentVo = new DepartmentVo();
                childDepartmentVo.setDepcode(department1.getDepcode());
                childDepartmentVo.setDepname(department1.getDepname());

                childDepartmentVoList.add(childDepartmentVo);
            }
            //将小科室的集合放到大科室当中
            departmentVo.setChildren(childDepartmentVoList);
            //将大科室添加到结果
            res.add(departmentVo);
        }
        return res;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode,depcode);
        if(department != null){
            return department.getDepname();
        }
        return null;
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }
}
